<?php

	namespace org\tekuna\demo\weblog\action\admin;
	
	use org\tekuna\framework\response\http\UrlRedirectResponse;

	use org\tekuna\demo\weblog\manager\ArticleManager;

	use org\tekuna\demo\weblog\model\Article;
	use org\tekuna\demo\weblog\ArticleKeyFilter;
	
	use org\tekuna\framework\filter\data\NoHtmlFilter;

	use org\tekuna\framework\filter\data\IntegerFilter;

	use org\tekuna\framework\request\Request;
	use org\tekuna\framework\action\ActionEvent;
	use org\tekuna\framework\action\AbstractAction;

	
	class SaveArticleAction extends AbstractAction {
		
		private
			$objArticleManager;
			
		
		public function execute(ActionEvent $objActionEvent, Request $objRequest) {
			
			// set filters
			$objRequest -> setPostFilter('id', new IntegerFilter());
			$objRequest -> setPostFilter('key', new ArticleKeyFilter());
			$objRequest -> setPostFilter('title', new NoHtmlFilter());
			$objRequest -> setPostFilter('text', new NoHtmlFilter());
			
			// get values
			$iArticleId = $objRequest -> getPostValue('id');
			$sKey = $objRequest -> getPostValue('key');
			$sTitle = $objRequest -> getPostValue('title');
			$sText = $objRequest -> getPostValue('text');
			
			// build entity
			$objArticle = new Article();
			$objArticle -> key = $sKey;
			$objArticle -> title = $sTitle;
			$objArticle -> text = $sText;
			
			if ($iArticleId === 0) {
				
				// new article
				$objArticle -> creationDate = time();
				$objArticle -> author = 'john'; // TODO: load from security
			}
			else {
				
				// existing article
				$objArticle -> id = $iArticleId;
			}
			
			// save entity
			$this -> objArticleManager -> save($objArticle);
			
			// redirect to article list
			$objArticleUrl = $objActionEvent -> buildActionUrl('/admin/articles/');
			return new UrlRedirectResponse($objArticleUrl);
		}
		
		
		public function setArticleManager(ArticleManager $objArticleManager) {
			
			$this -> objArticleManager = $objArticleManager;
		}
	}